package qj.util.swing;

import javax.swing.JTextField;

import qj.util.SwingUtil;
import qj.util.funct.F1;
import qj.util.funct.P1;

public class IntegerBox {
    JTextField comp;

    public IntegerBox(int num) {
        comp = new JTextField("" + num, 8);
        SwingUtil.focusSelect(comp);
    }

    public JTextField getComp() {
        return comp;
    }

    public void set(int num) {
        comp.setText("" + num);
    }

    public P1<Integer> set = new P1<Integer>() {
        public void e(Integer num) {
            set(num);
        }
    };

    public int get() {
        return Integer.parseInt(comp.getText());
    }

    public int decrementAndGet() {
        int num = get() - 1;
        set(num);
        return num;
    }

    public int incrementAndGet() {
        int num = get() + 1;
        set(num);
        return num;
    }

    public void onChange(final P1<Integer> onChange) {
        SwingUtil.onChange(comp, new F1<String, Boolean>() {

            public Boolean e(String text) {
                try {
                    int num = Integer.parseInt(text);
                    onChange.e(num);
                    return true;
                } catch (NumberFormatException e) {
                    return false;
                }
            }
        });
    }
}
